 <template>
    <div class="first_level_page">
        <svg style="position:absolute;width:0;height:0">
            <defs>
                <symbol viewBox="0 0 38 38" id="circleSelectedActive"> 
                    <circle cx="19" cy="19" r="19" stroke-width="0" fill="#ffa101"/>
                    <line x1="8" y1="18" x2="16" y2="27"
                    style="stroke:#fff;stroke-width:2"/>
                    <line x1="16" y1="27" x2="31" y2="12"
                    style="stroke:#fff;stroke-width:2"/>
                </symbol>

                <symbol viewBox="0 0 38 38" id="circleSelectedDefault"> 
                    <circle cx="19" cy="19" r="17" stroke="rgb(229,229,229)"
                    stroke-width="2" fill="white"/>
                </symbol>

                <symbol viewBox="0 0 38 38" id="squareSelectedActive">
                    <rect x="1" y="1" rx="6" ry="6" width="36"
                    height="36" style="fill:white;stroke:#ffa101;stroke-width:2"/>
                    <line x1="8" y1="18" x2="16" y2="27"
                    style="stroke:#ffa101;stroke-width:2"/>
                    <line x1="16" y1="27" x2="31" y2="12"
                    style="stroke:#ffa101;stroke-width:2"/>
                </symbol>

                <symbol viewBox="0 0 38 38" id="squareSelectedDefault">
                    <rect x="1" y="1" rx="6" ry="6" width="36"
                    height="36" style="fill:white;stroke:rgb(229,229,229);stroke-width:2"/>
                </symbol>
            </defs>
        </svg>
        <div class="need_pay_container">
            应付金额：<span class="need_pay">￥{{payMoney}}</span>
        </div>
        <div class="user_amount_container">
            <div class="user_amout_title">
                <img src="../../images/amountIcon.png">账户余额
            </div>
            <div class="user_amount_text">
                <span class="total_amount">账户余额：￥{{fmoney((theMoney), 2)}}</span>
                可用余额：<span class="available_amount">￥{{fmoney(useMoney, 2)}}</span>
            </div>
            <div class="icon_select_container" @click="amountSelect">
                <svg class="icon_style" >
                    <use :xlink:href="isAmount ? '#squareSelectedActive' : '#squareSelectedDefault'"></use>
                </svg>
            </div>
        </div>
        <div class="pay_type_container">
            <!-- <div class="pay_type_demo"> 
                <div class="pay_type_title">
                    <img src="../../../images/zhifubao.png">
                    <span>支付宝支付</span>
                </div>
                <div v-if="payType == 1" class="pay_type_value">
                    支付：<span>￥{{payTypeMoney}}</span>
                </div>
                <div class="icon_select_container" @click="payTypeSelect(1)">
                    <svg class="icon_style" >
                        <use :xlink:href="payType == 1 ? '#circleSelectedActive' : '#circleSelectedDefault'"></use>
                    </svg>
                </div>
            </div> -->
            <div class="pay_type_demo"> 
                <div class="pay_type_title">
                    <img src="../../images/weixin.png">
                    <span>微信支付</span>
                </div>
                <div v-if="payType == 2" class="pay_type_value">
                    支付：<span>￥{{fmoney(payTypeMoney,2)}}</span>
                </div>
                <div class="icon_select_container" @click="payTypeSelect(2)">
                    <svg class="icon_style" >
                        <use :xlink:href="payType == 2 ? '#circleSelectedActive' : '#circleSelectedDefault'"></use>
                    </svg>
                </div>
            </div>
            <div v-if="routerType == ''" class="pay_type_demo"> 
                <div class="pay_type_title">
                    <img src="../../images/yifenqi.png">
                    <span>翼分期</span>
                    <span class="right side_title">
                        您的授信额度剩余{{creditAmount ? fmoney(creditAmount, 2) : '0.00'}}
                    </span>
                </div>
                <div v-if="payType == 4" class="pay_type_value">
                    支付：<span>￥{{fmoney(payTypeMoney,4)}}</span>
                </div>
                <div class="icon_select_container" @click="payTypeSelect(4)">
                    <svg class="icon_style" >
                        <use :xlink:href="payType == 4 ? '#circleSelectedActive' : '#circleSelectedDefault'"></use>
                    </svg>
                </div>
            </div>
            <div v-if="routerType == ''" class="pay_type_demo"> 
                <div class="pay_type_title">
                    <img src="../../images/hdfk.png">
                    <span>货到付款</span>
                </div>
                <div v-if="payType == 3" class="pay_type_value">
                    支付：<span>￥{{payTypeMoney}}</span>
                </div>
                <div class="icon_select_container" @click="payTypeSelect(3)">
                    <svg class="icon_style" >
                        <use :xlink:href="payType == 3 ? '#circleSelectedActive' : '#circleSelectedDefault'"></use>
                    </svg>
                </div>
            </div>
        </div>
        <div class="next_step_btn_container">
            <div class="next_step_btn" @click="nextStep">立即支付</div>
        </div>
        <alert-tip v-if="showAlert" @closeTip="showAlert = false" :alertText="alertText"></alert-tip>
        <pay-password v-show="payShow" @closeMask="payShow = false" @pwdDone="pwdDone"></pay-password>
        <!-- 支付密码输入错误提示框 -->
        <div class="error_pwd" v-show="pwdErrorShow">
            <div class="error_main">
                <div class="error_text">
                    支付密码错误，请重试
                </div>
                <div class="error_btn">
                    <div class="forget_pwd" @click="forgetPwd">忘记密码</div>
                    <div class="try_again" @click="tryAgain">重试</div>
                </div>
            </div>
        </div>
        <div id="payTypeMoney" style="display:none">{{payTypeMoney}}</div>
        <transition name="router-slid" mode="out-in">
            <router-view></router-view>
        </transition>

        <transition name="loading">
            <loading v-if="showLoading"></loading>
        </transition>
    </div>
</template>
  
<script>
    import {mapState, mapMutations} from 'vuex'
    import {WXcheckbalance, validatePayPwd, WXbalanceFullPay, payInOrderCheck, getPayDate, payOrderUseNoneMoney, getJsConfig, getInOrderState,WXupdatePayChannel,getSellerInfo,WXcreditPay} from 'src/service/getData'
    import alertTip from 'src/components/common/alertTip'
    import payPassword from 'src/components/common/payPassword'
    import {fmoney} from 'src/config/mUtils'
    import {baseUrl} from 'src/config/env'
    import wx from 'weixin-js-sdk'
    import loading from 'src/components/common/loading'

    export default {
        data(){
            return{
                orderId: '', //订单ID
                payMoney: 0.00, //应付金额
               	payType: 0, //付款方式：1、支付宝；2、微信；3、货到付款
                isAmount: false, //是否使用账户余额
                payTypeMoney: 0.00, //除去账户余额部分需支付的金额
                showAlert: false,
                alertText: '',
                payShow: false,
                pwdErrorShow: false,
                buyInfo: '',
                voucherCode: '',
                warehouseCode: '',
                jsurl:'',
                wx,
                openId:'',
                baseUrl,
                payChannel:0,
                type:0,//1：在线支付，2：货到付款
                sellerAmount:0.00,//用户余额本金
                SellerRewardAmount:0.00,//用户余额奖励金
                frozenAmount:0.00,//冻结金额
                showLoading: true, //显示加载动画
                theMoney:0.00,//账户余额
                useMoney:0.00,//可用余额
                creditAmount:0.00,//授信额度
                routerType: '',
                pwdType: 0,//支付密码输入正确之后付款类型：1、全余额支付；2、翼分期
            }
        },
        components: {
            alertTip,
            payPassword,
            loading,
        },
        mounted(){
            this.initData();
            this.payMoney = this.$route.params.payMoney;
            this.orderId = this.$route.params.orderId;
            this.payTypeMoney = this.payMoney;
            this.buyInfo = this.$route.params.buyInfo;
            this.voucherCode = this.$route.params.voucherCode ? this.$route.params.voucherCode : '';
            this.warehouseCode = this.$route.params.warehouseCode;
            this.jsurl = location.href.split('#')[0];
            this.openId = localStorage.getItem('openId');
            this.routerType = this.$route.params.type ? this.$route.query.type : '';
        },
        beforeDestroy(){
            clearInterval(this.timer);
        },
        props:[],
        computed: {
            ...mapState([
                'userInfo', 
            ])
        },
        methods: {
            ...mapMutations([
                'RECORD_USERINFO', 'CLEAR_CART'
            ]),
            fmoney(s, n){
                return fmoney(s, n)
            },
            async initData(){
                let res = await getSellerInfo(this.userInfo.token); 
                this.showLoading = false;
                if(res.resultCode==200) {
                    this.sellerAmount = res.data.sellerAmount;
                    this.SellerRewardAmount = res.data.SellerRewardAmount;
                    this.frozenAmount = res.data.frozeAmount;
                    this.theMoney = this.sellerAmount + this.SellerRewardAmount;
                    this.useMoney = this.theMoney - this.frozenAmount;
                    this.creditAmount = res.data.creditAmount;
                }
            },
            amountSelect(){
                if(this.payType == 3 || this.payType == 4){
                    this.isAmount = false;
                }else{
                    this.isAmount = this.isAmount ? false : true;   
                }
                if(this.isAmount){
                    let availableAmoumt = fmoney((this.sellerAmount + this.SellerRewardAmount - this.frozenAmount),2);
                    if(this.payMoney - availableAmoumt > 0){
                        this.payTypeMoney = fmoney((this.payMoney - availableAmoumt),2);
                    }else{
                        this.payTypeMoney = 0.00;
                        this.payType = 0;
                    }
                }else{
                    this.payTypeMoney = fmoney(this.payMoney,2);
                }
            },
            async payTypeSelect(type){
                if(this.payTypeMoney == 0){
                    this.payType = 0;
                }else{
                    if(this.payType == type){
                        this.payType = 0;
                    }else{
                        if(this.isAmount && type == 3 || this.isAmount && type == 4){
                            this.payType = 0;
                        }else{
                            if(type == 4){
                                //翼分期授信额度不足，不能使用
                                if(this.payTypeMoney > Number.parseFloat(this.creditAmount ? this.creditAmount : 0.00)){
                                    this.payType = 0;  
                                    this.showAlert = true;
                                    this.alertText = '授信额度不足!';    
                                }else{//翼分期
                                    this.payType = type;
                                    this.type = 1;
                                    this.payChannel = 6;
                                }
                            }else{
                                this.payType = type;
                                if(type==2){ //微信支付
                                    this.type = 1;
                                    this.payChannel = 2;
                                }else if(type==3){//货到付款
                                    this.type = 2;
                                    this.payChannel = 0;
                                }
                            }
                        }
                    }
                }
                let data = await WXupdatePayChannel(this.userInfo.token,this.orderId,this.payChannel,this.type);
            },
            showTip(alertText){
                this.alertText = alertText;
                this.showAlert = true;
            },
            async nextStep(){
                this.showLoading = true;
                if(!this.isAmount && this.payType == 0){
                    this.showLoading = false;
                    this.showTip('请选择支付方式');
                    return;
                }
                if(this.routerType == ''){
                    //二次校验
                    let secondOc = await payInOrderCheck(this.userInfo.token, this.buyInfo, this.orderId, this.voucherCode, this.warehouseCode);
                    if(secondOc.resultCode == 0){
                        this.showLoading = false;
                        this.showTip(secondOc.resultMessage);
                        return;
                    }
                }
                if(this.isAmount){//组合支付
                    let flag = 0;
                    if(this.payType == 0){//全余额支付
                        flag = 1;
                    }else if(this.payType == 2){//微信+余额
                        flag = 3;
                    }
                    let cb = await WXcheckbalance(this.userInfo.token, this.orderId, flag);
                    if (cb.resultCode == 200) {
                        if(cb.data.money == 0){ //全余额支付
                            this.showLoading = false;
                            // console.log('yue')
                            if(cb.data.presentPassword != null && cb.data.presentPassword.length > 0){ // 有支付密码
                                this.payShow = true;
                                this.pwdType = 1;
                            }else{ // 没有支付密码
                                this.$router.push("/payment/setPayPwd")
                            }
                        }else{//微信+余额
                            let wxModelRes = await getPayDate(this.userInfo.token, localStorage.getItem("openId"), this.orderId);
                            if(wxModelRes.resultCode == 200){
                                let wxModel = wxModelRes.data;
                                this.orderId = wxModel.orderId;
                                this.winxinPay(wxModel);
                            }else{
                                this.showTip(wcModelRes.resultMessage);
                            }
                            this.showLoading = false;
                        }
                    }else{
                        this.showLoading = false;
                        this.showTip(cb.resultMessage)
                    }
                }else{//独立支付
                    if(this.payType == 2){//微信支付
                        let wxModelRes = await getPayDate(this.userInfo.token, localStorage.getItem("openId"), this.orderId);
                        this.showLoading = false;
                        if(wxModelRes.resultCode == 200){
                            let wxModel = wxModelRes.data;
                            this.winxinPay(wxModel);
                        }else{
                            this.showTip(wcModelRes.resultMessage);
                        }
                    }else if(this.payType == 3){//货到付款
                        let hdfkRes = await payOrderUseNoneMoney(this.userInfo.token, this.orderId);
                        this.showLoading = false;
                        if(hdfkRes.resultCode == 200){
                            this.$router.replace({ name: 'paySuccess', query: { payMoney: 0.00, text: '您已成功支付'}})
                        }else{
                            this.showTip(hdfkRes.resultMessage);
                            this.$router.replace('/order');  
                        }
                    }else if(this.payType == 4){//翼分期
                        let yiCb = await WXcheckbalance(this.userInfo.token, this.orderId, 4);
                        if(yiCb.resultCode == 200){                            
                            this.showLoading = false;
                            if(yiCb.data.presentPassword != null && yiCb.data.presentPassword.length > 0){ // 有支付密码
                                this.payShow = true;
                                this.pwdType = 2;
                            }else{ // 没有支付密码
                                this.$router.push("/payment/setPayPwd")
                            }
                        }else{
                            this.showLoading = false;
                            this.showTip(yiCb.resultMessage);
                        }
                    }
                }

            },
            async pwdDone(pay_pwd){
                this.payShow = false;
                this.showLoading = true;
                let res = await validatePayPwd(this.userInfo.token, pay_pwd);
                if(res.resultCode == 200){                    
                    if(this.pwdType == 1){//全余额支付
                        let response = await WXbalanceFullPay(this.userInfo.token, this.orderId);
                        this.showLoading = false;
                        if(response.resultCode == 200){
                            this.$router.replace({ name: 'paySuccess', query: { payMoney: this.payMoney, text: '您已成功支付'}})
                        }else{
                            this.showTip(response.resultMessage);
                        }
                    }else if(this.pwdType == 2){//翼分期
                        let response = await WXcreditPay(this.userInfo.token, this.orderId);
                        this.showLoading = false;
                        if(response.resultCode == 200){
                            this.$router.replace({ name: 'paySuccess', query: { payMoney: this.payMoney, text: '您已成功支付'}})
                        }else{
                            this.showTip(response.resultMessage);
                        }
                    }
                }else{
                    this.pwdErrorShow = true;
                    this.showLoading = false;
                }
            },
            forgetPwd(){
                this.pwdErrorShow = false;
                this.$router.push("/payment/forgetPayPwd")
            },
            tryAgain(){
                this.pwdErrorShow = false;
                this.payShow = true;
            },
            async winxinPay(wxModel){
                this.wx.chooseWXPay({
                    timestamp: wxModel.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: wxModel.nonceStr1, // 支付签名随机串，不长于 32 位
                    package: wxModel.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: wxModel.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: wxModel.paySign, // 支付签名
                    success: function (res) {// 支付成功后的回调函数      

                        // 支付成功后的回调函数
                        if (res.errMsg == "chooseWXPay:ok") {  
                            var payMoney = document.getElementById('payTypeMoney').innerHTML;
                            var text="您已成功支付";
                            window.location.replace="http://api.zhongjiubianli.com/wechat/sellers/home#/payment/paySuccess?payMoney="+payMoney+"&text="+text;
                            // window.location.href=baseUrl+"/wechat/sellers/home";
                        } else {  
                            alert(res.errMsg);  
                        }     
                    }/*,
                    cancel: function (res) {
                        window.history.go(-1);
                    },
                    fail: function (res) {
                        alert("支付失败！");
                    },*/
                });
            },
            async getJsConfig(){
                this.showLoading = true;
                let data = await getJsConfig(this.userInfo.token,this.jsurl);
                this.showLoading = false;
                let obj = data.data;
                this.wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: obj.appId, // 必填，公众号的唯一标识
                    timestamp: obj.timestamp, // 必填，生成签名的时间戳
                    nonceStr: obj.nonceStr, // 必填，生成签名的随机串
                    signature: obj.signature,// 必填，签名，见附录1
                    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','chooseWXPay','scanQRCode'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });

            },
        },
        watch:{
            "jsurl":"getJsConfig"
        }
    }
</script>
  
<style lang="scss" scoped>
    @import 'src/style/mixin';
    .need_pay_container{
        @include wh(100%, 1.02rem);
        background: #fff;
        @include sc(.32rem, #333);
        line-height: .32rem;
        padding-top: .36rem;
        padding-left: .24rem;
        margin-bottom: .2rem;
        .need_pay{
            color: $orange;
        }
    }
    .user_amount_container{
        background: #fff;
        @include wh(100%, 1.38rem);
        padding-left: .24rem;
        position: relative;
        margin-bottom: .2rem;
        .user_amout_title{
            @include sc(.3rem, #333);
            padding-top: .26rem;
            line-height: .38rem;
            height: .64rem;
            img{
                @include wh(.4rem, .38rem);
                vertical-align: middle;
                margin-right: .22rem;
            }
        }
        .user_amount_text{
            @include sc(.26rem, #666);
            margin-top: .22rem;
            line-height: .26rem;
            height: .26rem;
            .total_amount{
                margin-right: .35rem;
            }
            .available_amount{
                color: $orange;
            }
        }
    }
    .icon_select_container{
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        padding: 0 .2rem;
        padding-top: .3rem;
        svg{
            @include wh(.38rem, .38rem);
            float: left;
        }
    }
    .pay_type_container{
        background: #fff;
        .pay_type_demo{
            @include wh(100%, 1.42rem);
            padding-left: .24rem;
            border-bottom: .01rem solid #ededed;
            position: relative;
            .pay_type_title{
                padding-top: .28rem;
                @include sc(.3rem, #333);
                line-height: .4rem;
                height: .68rem;
                img{
                    @include wh(.4rem, .4rem);
                    vertical-align: middle;
                    margin-right: .22rem;
                }
                .side_title{
                    @include sc(.28rem, #666);
                    margin-right: .8rem;
                }
            }
            .pay_type_value{
                @include sc(.26rem, #666);
                margin-top: .24rem;
                line-height: .26rem;
                height: .26rem;
                span{
                    color: $orange;
                }
            }
        }
        .pay_type_demo:last-child{
            border-bottom: none;
        }
    }
    .next_step_btn_container{
        margin-top: .42rem;
        @include wh(100%, .88rem);
        padding: 0 .26rem;
        .next_step_btn{
            @include wh(100%, .88rem);
            text-align: center;
            @include sc(.34rem, #fff);
            line-height: .88rem;
            background: $orange;
            border-radius: .1rem;
        }
    }
    .error_pwd{
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, .6);
        .error_main{
            position: absolute;
            top: 45%;
            left: 1rem;
            right: 1rem;
            background: #fff;
            border: none;
            border-radius: .2rem;
            height: 1.8 rem;
            margin-top: -.9rem;
            .error_text{
                @include wh(100%, 1rem);
                line-height: 1rem;
                @include sc(.32rem, #333);
                text-align: center;
                font-weight: bold;
                border-bottom: .01rem solid #dedede;
            }
            .error_btn{
                display: flex;
                text-align: center;
                line-height: .8rem;
                @include wh(100%, .8rem);
                .forget_pwd{
                    flex: 1;
                    border-right: .01rem solid #dedede;
                    @include sc(.34rem, $orange);
                }
                .try_again{
                    flex: 1;
                    @include sc(.34rem, $orange);
                }
            }
        }
    }
</style>
